package cn.zl.springbootmqtt.sub;

import cn.zl.springbootmqtt.util.ymlUtil;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @Description:
 * @Author: zllwsy
 * @Date: 2020/10/27 17:21
 */
public class MqttSubClient {
    private MqttClient client;

    private static volatile MqttSubClient mqttSubClient = null;

    public static MqttSubClient getInstance() {
        if (null == mqttSubClient) {
            synchronized (MqttSubClient.class) {
                if (null == mqttSubClient) {
                    mqttSubClient = new MqttSubClient();
                }
            }
        }
        return mqttSubClient;
    }

    private MqttSubClient() {
       connect();
    }

    private void connect() {
        try {
            client = new MqttClient(ymlUtil.MQTT_HOST, "subServer", new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            //连接选项
            options.setCleanSession(false);
            options.setUserName(ymlUtil.MQTT_USER_NAME);
            options.setPassword(ymlUtil.MQTT_PASSWORD.toCharArray());
            options.setConnectionTimeout(ymlUtil.MQTT_TIMEOUT);
            options.setKeepAliveInterval(ymlUtil.MQTT_KEEP_ALIVE);
            //保留会话
            options.setCleanSession(true);
            //设置回调
            client.setCallback(new SubCallBack());
            //建立连接
            client.connect(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 订阅某个主题，qos默认为0
     * @param topic
     */
    public void subscribe(String topic) {
        subscribe(topic, 0);
    }

    /**
     * 订阅某个主题
     * @param topic
     * @param qos
     */
    public void subscribe(String topic, int qos) {
        try {
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

